package com.xzh.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzh.model.Teachers;
import com.xzh.service.TeachersService;
import com.xzh.util.JsonResult;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/teachers")
public class TeachersApi {
    private TeachersService teachersService;
    @Autowired
    public void setTeachersService(TeachersService teachersService){
        this.teachersService = teachersService;
    }

    @GetMapping
    public ResponseEntity<JsonResult<?>> selectAll(@RequestParam(defaultValue = "1") Integer pageNo,
                                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                                   Teachers  teachers){
        Page<Teachers> page = new Page<>(pageNo, pageSize);
        page = teachersService.selectAll(page, teachers);
        return ResponseEntity.ok(JsonResult.success(page));

    }

    @PostMapping
    public ResponseEntity<JsonResult<?>> add(@Valid @RequestBody Teachers teachers){
        boolean result = teachersService.save(teachers);
        if(result){
            return ResponseEntity.ok(JsonResult.success());
        }else {
            return ResponseEntity.ok(JsonResult.fail("添加失败"));
        }
    }

    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@Valid @RequestBody Teachers teachers){
        boolean result = teachersService.updateById(teachers);
        if(result){
            return ResponseEntity.ok(JsonResult.success());
        }else {
            return ResponseEntity.ok(JsonResult.fail("更新失败"));
        }
    }

    @DeleteMapping
    public ResponseEntity<JsonResult<?>> delete(@RequestBody Integer[] ids){
        int count = teachersService.deleteByIds(List.of(ids));
        if(count > 0){
            return ResponseEntity.ok(JsonResult.success(count));
        }else {
            return ResponseEntity.ok(JsonResult.fail("删除失败"));
        }
    }

    @GetMapping("/statistics")
    public ResponseEntity<JsonResult<?>> statistics(){
        List<Map<String, Object>> result = teachersService.statistics();
        return ResponseEntity.ok(JsonResult.success(result));
    }
}
